//
//  WmcCancellationValidationVC.swift
//  YPWatermarkCamera
//
//  Created by 马涛 on 2022/6/20.
//

import RxCocoa
import UIKit
import YPBedrock

// MARK: - 扩展WmcCancellationValidationVC + WmcNavigatorProtocol

extension WmcCancellationValidationVC: WmcNavigatorProtocol {
    static func navigationPaths() -> [WmcNavigatorManager.Path] {
        return [.cancellationValidation]
    }

    static func willMakeNavigationVC(with parms: WmcNavigatorManager.Parms) -> UIViewController {
        var vc = UIViewController()
        if let vm = parms.context as? WmcCancellationFeedbackVM {
            let viewModel = WmcCancellationValidationVM()
            viewModel.reason = vm.reason
            viewModel.imgUrls = vm.imgUrls
            vc = WmcCancellationValidationVC(viewModel)
        }
        return vc
    }
}

// MARK: - 扩展WmcCancellationValidationVC + WmcVMProtocol

extension WmcCancellationValidationVC: WmcVMProtocol {
    typealias VMType = WmcCancellationValidationVM
}

// MARK: - [WmcCancellationValidationVC]

class WmcCancellationValidationVC: WmcBaseVC {
    // Lifecycle

    deinit {
        /// 释放当前页面timer
        validationInput.releaseTimer()
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        title = "注销账号"
    }

    // Internal

    lazy var titleTagLabel: UILabel = {
        let view = UILabel()
        view.font = 16.yp.uiFont(weight: .bold)
        view.textColor = UIColor.wmc_blackH1_000000
        view.text = "请填写动态验证码，进行身份验证"
        return view
    }()

    lazy var phoneLabel: UILabel = {
        let view = UILabel()
        let attriS = "当前绑定手机号为：".yp.makeAttributed { make in
            make.set(font: 14.yp.uiFont(weight: .regular))
                .set(foregroundColor:UIColor.wmc_grayH7_808080)
        }
        let phoneAttriS = viewModel.tel.yp.makeAttributed { make in
            make.set(font: 14.yp.uiFont(weight: .regular))
                .set(foregroundColor:UIColor.wmc_blackH1_000000)
        }
        attriS.append(phoneAttriS)
        view.attributedText = attriS
        return view
    }()

    lazy var validationInput: WmcValidationCodeView = {
        let view = WmcValidationCodeView()
        return view
    }()

    lazy var validationButton: UIButton = {
        let view = UIButton()
        view.setTitle("验证", for: .normal)
        view.setTitleColor(UIColor.wmc_white_FFFFFF, for: .normal)
        view.backgroundColor = UIColor.wmc_grayH16_EBEBEB
        view.layer.cornerRadius = 3
        view.clipsToBounds = true
        return view
    }()

    override func makeUI() {
        makeNavView(showShadow: false)

        addSubview(titleTagLabel)
        addSubview(phoneLabel)
        addSubview(validationInput)
        addSubview(validationButton)

        titleTagLabel.snp.makeConstraints { make in
            make.top.equalTo(navView.snp.bottom)
            make.left.equalTo(37)
            make.right.equalTo(-37)
        }
        phoneLabel.snp.makeConstraints { make in
            make.top.equalTo(titleTagLabel.snp.bottom).offset(15)
            make.left.equalTo(37)
            make.right.equalTo(-37)
        }
        validationInput.snp.makeConstraints { make in
            make.top.equalTo(phoneLabel.snp.bottom).offset(32)
            make.left.equalTo(37)
            make.right.equalTo(-37)
        }
        validationButton.snp.makeConstraints { make in
            make.top.equalTo(validationInput.snp.bottom).offset(47)
            make.left.equalTo(37)
            make.right.equalTo(-37)
            make.height.equalTo(42)
        }
    }

    /// 变化函数
    /// - Parameter str: str description
    /// - Returns: description
    func transformString(str: String?) -> UIColor {
        if let t = str {
            if t.count > 0 {
                return UIColor.wmc_mainTheme
            } else {
                return UIColor.wmc_grayH16_EBEBEB
            }
        } else {
            return UIColor.wmc_grayH16_EBEBEB
        }
    }

    /// 检查长度是否大于0
    /// - Parameter str: str description
    /// - Returns: description
    func checkString(str: String?) -> Bool {
        if let t = str {
            if t.count > 0 {
                return true
            } else {
                return false
            }
        } else {
            return false
        }
    }

    override func bindViewModel() {
        

        /// 限制输入字符个数
        validationInput.textfield.rx.text.orEmpty.map { text -> Bool in
            text.count > 4
        }.share(replay: 1).subscribe(onNext: {[weak self] valid in
            guard let weakSelf = self else { return }
            if  valid {
                let index =  weakSelf.validationInput.textfield.text!.index( weakSelf.validationInput.textfield.text!.startIndex, offsetBy: 4)
                weakSelf.validationInput.textfield.text = String( weakSelf.validationInput.textfield.text![..<index])
            }
        }).disposed(by: rx.disposeBag)
        
        viewModel.cancelResult.skip(1).bind { result in
            guard let res = result,let head = res.head,let msg = head.msg else { return }
            WmcLogManager.Log("注销结果 ====== \(res)")
            if head.code == 500 {
                WmcHudManager.toast(msg)
            }
            if head.code == 200 {
                WmcNavigatorManager.push(.cancellationConfirm)
            }
        }.disposed(by: rx.disposeBag)
    }

    override func bindViewAction() {
        validationInput.textfield.rx.text.map {[weak self] text in
            guard let weakSelf = self else { return UIColor.wmc_grayH16_EBEBEB }
            return weakSelf.transformString(str: text)
        }.bind(to: validationButton.rx.backgroundColor).disposed(by: rx.disposeBag)

        validationInput.textfield.rx.text.map {[weak self] text in
            guard let weakSelf = self else { return false }
            return weakSelf.checkString(str: text)
        }.bind(to: validationButton.rx.isEnabled).disposed(by: rx.disposeBag)
     
        validationInput.textfield.rx.text.bind { [weak self] text in
            guard let weakSelf = self else { return }
            weakSelf.viewModel.code = text
        }.disposed(by: rx.disposeBag)
        
        validationButton.yp.addEvent() { [weak self] _ in
            guard let weakSelf = self else { return }
            weakSelf.viewModel.cancelAccount()
        }

        validationInput.validationButton.yp.addEvent() { [weak self] btn in
            guard let weakSelf = self else { return }
            WmcLogManager.Log("获取验证码")
            btn.countdown(second: 60, isCountdown: true) { info in
                print(info)
            }
            weakSelf.viewModel.sendCode()
        }
    }
}
